﻿<?php
require_once 'config.php';
// SELECT * FROM timkiem WHERE MATCH (content)
    // AGAINST ('+rộng +buồn' IN BOOLEAN MODE)
//$commonWords = array('cho', 'tôi', 'bạn', 'chúng ta', 'hỏi', 'đáp', 'trả', 'muốn');

function getSearchWords($searchText)
{
	//$commonWords = array('');
	$searchText = trim($searchText);
	if ($searchText == '')
	{
		return NULL;
	}
	
	$words = explode(' ', $searchText);
	if (count($words) == 0)
	{
		return NULL;
	}
	
	//$nwords = array_diff($commonWords, $words);
	$nwords = $words;

	$usefulWords = array();
	for ($i = 0; $i < count($nwords); $i++)
	{
		if (strlen($nwords[$i])  >= 3)
		{
			$usefulWords[] = $nwords[$i];
		}
	}
	
	return $usefulWords;
}

function getSearchItemQuery($searchText, $scat, $sopt)
{
	$words = getSearchWords($searchText);
	$searchText = '';
	foreach ($words as $word)
	{
		$searchText .= ($sopt == 'cx'? '+' : '')."$word ";
	}

	$sql_bb = " SELECT tk.id, tk.item_id, tk.table_id, bb.tenbb as ten, bb.tomtat_bb as tomtat, bb.noidung_bb as noidung
				FROM timkiem tk join baibao bb ON tk.item_id = bb.id
				WHERE table_id = 1 AND MATCH (content)
				AGAINST ('" . $searchText . "' IN BOOLEAN MODE) ";
	$sql_dt = " SELECT tk.id, tk.item_id, tk.table_id, dt.tendt as ten, dt.tomtat_dt as tomtat, dt.noidung_dt as noidung
				FROM timkiem tk join detai dt ON tk.item_id = dt.id
				WHERE table_id = 2 AND MATCH (content)
				AGAINST ('" . $searchText . "' IN BOOLEAN MODE) ";
	$sql_sm = " SELECT tk.id, tk.item_id, tk.table_id, sm.chude as ten, sm.tomtat as tomtat, sm.noidung as noidung
				FROM timkiem tk join hoithao sm ON tk.item_id = sm.id
				WHERE table_id = 3 AND MATCH (content)
				AGAINST ('" . $searchText . "' IN BOOLEAN MODE) ";
	$sql = "";
	
	switch ($scat)
	{
		case 1:
			$sql = $sql_bb;
			break;
		case 2:
			$sql = $sql_dt;
			break;
		case 3:
			$sql = $sql_sm;
			break;
		default:
			$sql = " ($sql_bb) UNION ($sql_dt) UNION ($sql_sm) ";
			break;
	}
	
	//echo '<br><br><br><br><br><br><br><br><br>'.$sql;
	return $sql;
	
}
?>